﻿<?php
/**
\cond
ooooo                        
`888'                        
 888  oo.ooooo.  oooo    ooo 
 888   888' `88b  `88.  .8'  
 888   888   888   `88..8'   
 888   888   888    `888'    
o888o  888bod8P'     .8'     
       888       .o..P'      
      o888o      `Y8P'       
\endcond

\file coffee.php
\brief	Front-end pour la bibliothèque coffee, qui permet de compiler du coffeescript.
\author 	: 	Loïc Coenen
\date 		:	29/06/2013

**/

require 'Init.php';
require 'JShrink.php';


/**

\brief Classe principale du compilateur coffee
**/
class coffee {


	/**
		\brief Constructeur
		\param maat Une instance de maat
	**/
	function __construct($maat){
		
		CoffeeScript\Init::load();
		
		$maat->route('js/$1', array($this, 'compile'));
		
		$this->cache_directory = 'cache/js/';
		
	}

	/**
		Compilation d'un fichier coffeescript => JS
	*/
	public function compile($args, $tpl)	{
	
		try	{
	
			header("Content-type:text/javascript");
	
			$file = 'cs/' . $args[1];
			$cache_file = $this->cache_directory . $args[1];
			
			if(file_exists($cache_file) && filemtime($file) < filemtime($cache_file)){
			
				echo file_get_contents($cache_file);
				return;
			
			}
		
			$coffee = file_get_contents($file);
		
			if(!$coffee){
		
				throw new Exception('Impossible de trouver ' . $file);
			
			}

			$js = JShrink::minify(CoffeeScript\Compiler::compile($coffee, array('filename' => $file)));
			
			file_put_contents($cache_file);
			
			echo $js;
	  
		}
		catch (Exception $e) {

			header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);

			echo $e->getMessage();

		}

	}

};

?>
